package com.xuxin.pda.activity;

import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.xuxin.pda.R;
import com.xuxin.pda.base.BaseConstant;
import com.xuxin.pda.base.BasePDAActivity;
import com.xuxin.pda.bean.LoginBean;
import com.xuxin.pda.contract.LoginContract;
import com.xuxin.pda.presenter.LoginPresenter;
import com.xuxin.pda.utils.ACache;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by xu_xin
 * Created on 2020/12/24 0024
 * 登录
 */
public class LoginActivity extends BasePDAActivity implements LoginContract.View {
    private final LoginContract.Presenter presenter = new LoginPresenter(this);
    @BindView(R.id.login_num)
    EditText login_num;
    @BindView(R.id.button)
    Button button;
    private ACache aCache;
    private String userNo;

    @Override
    public void setContentView() {
        setContentView(R.layout.activity_login);
    }

    @Override
    public void initView() {
        button.setText("登录");
    }

    @Override
    public void initData() {
        aCache = ACache.get(context);
    }

    @Override
    public void onComplete() {
        dismiss();
    }

    @Override
    @OnClick({R.id.button})
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.button) {
            userNo = login_num.getText().toString();
            if (!StringUtils.isEmpty(userNo)) {
                popup.setTitle("登陆中...").show();
                handler.sendEmptyMessageDelayed(0, 500);
            } else {
                ToastUtils.showShort("请输入工号");
            }
        }
    }

    @Override
    public void onSuccess(LoginBean loginBean) {
        if (null != loginBean) {
            aCache.put(BaseConstant.userId, loginBean.getResult().getUserId());
            aCache.put(BaseConstant.userName, loginBean.getResult().getName());
            aCache.put(BaseConstant.userNo, loginBean.getResult().getENum());
            ActivityUtils.startActivity(MainActivity.class);
            finish();
        }
    }

    private final Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == 0) {
                presenter.login(userNo);
            }
            return false;
        }
    });

    @Override
    public void onPDASuccess(String message) {
        if (message.startsWith("user")) {
            userNo = message;
            popup.setTitle("登陆中...").show();
            handler.sendEmptyMessageDelayed(0, 500);
        } else {
            ToastUtils.showShort("二维码格式错误");
        }
    }
}